<?php

namespace App\Http\Controllers\Api;

use App\AboutUs;
use App\Banner;
use App\Classify;
use App\Comment;
use App\DemandImg;
use App\Demands;
use App\Distribution;
use App\ExpertLabel;
use App\Experts;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatModelMsg;
use App\Industries;
use App\News;
use App\NewsLabel;
use App\SearchKeywordRecord;
use App\UnitGrade;
use App\Units;
use App\User;
use App\UserAttentionDemand;
use App\UserInfo;
use App\UserSearchRecord;
use App\VipRule;
use App\Withdraw;
use Endroid\QrCode\QrCode;
use http\Exception\RuntimeException;
use Illuminate\Bus\Dispatcher;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;

class OtherController extends Controller
{
    /**
     * 获取banner列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBannerList(Request $request){
        $allBanner = Banner::whereStatus(1)->orderBy("sort","asc")->orderBy("created_at","desc")->get();
        if(count($allBanner) > 0){
            foreach ($allBanner as $banner){
                /** @var Banner $banner */
                $banner->img_url = FileManager::getImgUrl($banner->img_id);
            }
        }

        return response()->json(["level"=>"success","message"=>"获取成功","data"=>$allBanner]);
    }

    /**
     * 获取行业列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIndustryList(Request $request){
        $industryLis = Industries::orderBy('sort','asc')->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $industryLis]);
    }

    /**
     * 关于我们
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAboutUs(Request $request){
        $aboutUs = AboutUs::whereStatus(1)->orderBy('created_at','desc')->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $aboutUs]);
    }

    public function getImgUrlTOImgId(Request $request){
        $imgId = !is_null($request->get('img_id')) ? $request->get('img_id') : 0;

        $imgUrl = FileManager::getImgUrl($imgId);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $imgUrl]);
    }

    public function getClassify(Request $request){
        $type=$request->get('type');

        $classify=Classify::whereType($type)->whereIsShow(1)->orderBy('sort','asc')->get();
        if(count($classify) > 0){
            foreach($classify as $val){
                $val->img_url = FileManager::getImgUrl($val->img_id);
            }
        }
        return response()->json(['level' => 'success','message' => '获取成功','data' => $classify]);
    }

    public function getUnitGradeList(Request $request){
        $unitGradeList = UnitGrade::orderBy('level','asc')->orderBy('created_at','desc')->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $unitGradeList]);
    }
    
    public function getOssImgPath(Request $request){
        $path = 'http://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/peoplesAssociation/';

        return response()->json(['level' => 'success','message' => '获取成功','data' => $path]);
    }

    /**
     * 获取模板id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getTemplate(Request $request){
        $type = !is_null($request->get('type')) ? $request->get('type') : '';

        $vipTemplate = 'IOKBwvpDKhHnQ64NWCJFotfHrfM6cwQ3_mUcbIkEni0';
        $newTemplate = 'UxHNjS-4G985nMP8Wx51w7cgosHJR-nXukhtvNuu7g4';
        $personAuth  = 'z5LljFTvA8iKBv_g_dIuDNquBtsfTOhS6X09RFiyv1k';
        $companyAuth = 'LM5TbgFvtrZqaawq6JCMljfPB7LUBK8FkTk7IzORDCw';
        $contentAuthing = '6AlbQAzEDv6xu_kuuPohdxCcbTbPvNUJ14f1DGlrfO8';
        $contentAuthResult = 'noDqbRx0UaEmpobPtOizFSQ0e8TwEq2PZtuQAfL_Aqo';//审核结果通知
        $expertAppoint = "mM-OylmNAPMsrN2JWLiN7JV3EknCiybFdrieMP0445M";//预约状态提醒
        $demandResult = "Hbb70MYvS_JjK3WCi3aUgKi0e-j___lRsJu9p21Igj4";//用于需求对接结果通知

        if($type == 'vip'){
            $data = [$vipTemplate];
        }elseif($type == 'demand'){
            $data = [$newTemplate];
        }elseif($type == 'personal_auth'){
            $data = [$personAuth];
        }elseif($type == 'company_set') {
            $data = [$companyAuth];
        }elseif($type == 'content_authing'){
            $data = [$contentAuthing];
        }elseif($type == 'content_auth_result') {
            $data = [$contentAuthResult];
        }elseif($type == 'expert_appoint') {
            $data = [$expertAppoint];
        }elseif($type == 'demand_result') {
            $data = [$demandResult];
        }else{
            $data = [$vipTemplate,$newTemplate,$personAuth,$companyAuth,$contentAuthResult];
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $data]);
    }

    public function searchSomething(Request $request){
        $user = UserManager::isLogin($request);
        $keyword    = $request->get('keyword');
        $page   =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit  =!is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page_info=[
            'page'          =>$page,
            'limit'         =>$limit,
            'demand_total'  => 0,
            'news_total'    => 0,
            'unit_total'    => 0,
            'expert_total'  => 0,
        ];
        $page=$page-1;
        $result=[
          'demand'    => [],
          'news'      => [],
          'vip_unit'  => [],
          'expert'    => []
        ];

        if (!trim($keyword))
            return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$result]);
        //TODO 记录搜索关键词
        $user_id = $user ? $user->id : 0;
        self::addSearchRecord($keyword,$user_id,$request->ip());
        $Demand = Demands::where('title','like','%'.trim($keyword).'%')
                ->orWhere('content','like','%'.trim($keyword).'%');
        $page_info['demand_total']=$Demand->count();
        $demands =$Demand->offset($page * $limit)->limit($limit)->get();

        $news   =News::whereStatus(1)->where('title','like','%'.trim($keyword).'%');
        $page_info['news_total']=$news->count();
        $news   =$news->offset($page * $limit)->limit($limit)->get(['id','title','img_id','desc','type','video_id','advert_img_id','created_at']);

        $vip_unit=Units::where('name','like','%'.trim($keyword).'%');
        $page_info['unit_total']=$vip_unit->count();
        $vip_unit=$vip_unit->offset($page * $limit)->limit($limit)->get();
        if (count($demands) > 0){
            /** @var Demands $demand */
            foreach ($demands as $demand){
                $classify               =Classify::whereId($demand->classify_id)->first();
                $industry               =Industries::whereId($demand->industry_id)->first();
                $imgs                   =DemandImg::whereDemandId($demand->id)->get();
                $url_array=[];
                if (count($imgs) > 0){
                    foreach ($imgs as $img){
                        $url=FileManager::getImgUrl($img->img_id);
                        array_push($url_array,$url);
                    }
                }
                $demand->classify_name  = $classify ? $classify->name :'其他';
                $demand->industry_name  = $industry ? $industry->name :'其他';
                $demand->img_array_url  = $url_array;
                $demand->is_collection  = $user ? (UserAttentionDemand::whereUserId($user->id)->whereDemandId($demand->id)->first() ? 1 :2 ) : 2;


            }
        }
        if (count($news) > 0){
            /** @var News $item */
            foreach ($news as $item){
                $item->img_url          =FileManager::getImgUrl($item->img_id);
                $item->advert_img_url   =FileManager::getImgUrl($item->advert_img_id);
                $item->video_url        =FileManager::getVideoUrl($item->video_id);
                $item->lable_array      =NewsLabel::whereNewsId($item->id)->pluck('name')->toArray();
//                $item->comments=$comments;
            }
        }
        if (count($vip_unit) > 0){
            foreach ($vip_unit as $item){
                $industry           =Industries::whereId($item->industry_id)->first();
                $item->photo_url    =FileManager::getImgUrl($item->photo_id);
                $item->industry_name=$industry ? $industry->name : '其他';
            }
        }

        $expertIds = ExpertLabel::where('name','like','%'.trim($keyword).'%')->pluck('expert_id');

        $expertList = Experts::whereIn('id',$expertIds)
                              ->orWhere('realname','like','%'.trim($keyword).'%')
                              ->orWhere('position','like','%'.trim($keyword).'%')
                              ->orWhere('strengths','like','%'.trim($keyword).'%')
                              ->whereIsAuth(1);

        $page_info['expert_total'] = $expertList->count();

        $expertList = $expertList->offset($page * $limit)->limit($limit)->get();
        if(count($expertList) > 0){
            foreach ($expertList as $expert) {
                $userBasicInfo = CommonManager::getUserBasicInfo($expert->user_id);
                if(is_null($expert->phone) || trim($expert->phone) == ""){
                    if(count($userBasicInfo) > 0 && isset($userBasicInfo['phone'])){
                        $expert->phone = $userBasicInfo['phone'];
                    }
                }
                $expert->photo_url    = FileManager::getImgUrl($expert->photo_id);
                $expert->expert_label = CommonManager::getExpertLabel($expert->id);
                $expert->auth_status  = CommonManager::getAuthReviewStatus($expert->is_auth);
            }
        }

        $result['demand']   = $demands;
        $result['news']     = $news;
        $result['vip_unit'] = $vip_unit;
        $result['expert']   = $expertList;
        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$result]);

    }

    public function getSearchKeyword(Request $request){
        $user       = UserManager::isLogin($request);
        $user_id    = $user ? $user->id : 0;
        if ($user_id){
            $user_keyword   =UserSearchRecord::whereUserId($user_id)->orderBy('id','desc')->offset(0)->limit(8)->pluck('keyword')->toArray();
        } else {
            $user_keyword   =[];
        }
        $keyword            =SearchKeywordRecord::orderBy('number')->offset(0)->limit(6)->pluck('keyword')->toArray();

        $result=[
            'my_history'        =>$user_keyword,
            'recommend_keyword' =>$keyword
        ];
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$result]);


    }

    public function delMykeywordRecord(Request $request){
        $user       = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $user_keyword   =UserSearchRecord::whereUserId($user->id)->delete();
        return response()->json(['level'=>'success','message'=>'清除成功']);

    }

    public function getOpenIdTest(){
        dump(WechatModelMsg::getUserList());
    }
    public static function addSearchRecord($keyword,$user_id=0,$ip=''){
        if ($keyword){
            if ($user_id){
                $thisRecord = UserSearchRecord::whereKeyword($keyword)->whereUserId($user_id)->orderBy('created_at','desc')->first();
                if($thisRecord){
                    if(strtotime($thisRecord->created_at) + 300 <= time()){
                        $thisRecord             = new UserSearchRecord();
                        $thisRecord->user_id    = $user_id;
                        $thisRecord->keyword    = $keyword;
                        if ($ip)
                            $thisRecord->ip     = $ip;
                        $thisRecord->save();
                    }
                } else {
                    $thisRecord = new UserSearchRecord();
                    $thisRecord->user_id   = $user_id;
                    $thisRecord->keyword   = $keyword;
                    if ($ip)
                        $thisRecord->ip    = $ip;
                    $thisRecord->save();
                }
            }
            $keyword_num = SearchKeywordRecord::whereKeyword($keyword)->first();
            if ($keyword_num){
                $keyword_num->number    =$keyword_num->number+1;
                $keyword_num->save();
            } else {
                $keyword_num            =new SearchKeywordRecord();
                $keyword_num->keyword   =$keyword;
                $keyword_num->save();
            }


        }
        return 1;
    }

    public function showQrcode(Request $request){
        $content = $request->get("content");

        $qrCode = new QrCode();
        $qrCode
            ->setText($content)
            ->setSize(250)
            ->setPadding(10)
            ->setErrorCorrection('high')
            ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
            ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
            ->setImageType(QrCode::IMAGE_TYPE_PNG)
        ;

        $qrcodeContent = $qrCode->getImage();

        $qrcodeContentImg = Image::make($qrcodeContent);

        $response = response()->make($qrcodeContentImg->encode('png'));
        $response->header('Content-Type', 'image/png');

        return $response;
    }
}
